package com.github.dtkavin.bgq.utils

import java.sql.{Connection, DriverManager, ResultSet}

import scala.collection.mutable.ArrayBuffer

/**
  * @author wangliping
  */
object MysqlUnits {
  val url: String = "jdbc:mysql://test-bigdata-worker001.yf.apus.com:3306/apus_atlas"
  val username: String = "admin_rw"
  val password: String = """DpvI#a&xcudNKS0r"""

  private def getConnection(): Connection = {
    classOf[com.mysql.jdbc.Driver]
    DriverManager.getConnection(url, username, password)
  }

  def query[T](sql: String, function: Function[ResultSet, T]): T = {
    val conn = this.getConnection
    try {
      val stat = conn.createStatement()
      val rt = stat.executeQuery(sql)
      function.apply(rt)
    } finally {
      conn.close
    }
  }

  def query[T](sql: String, rowMapper: RowMapper[T]): List[T] = {
    val conn = this.getConnection
    try {
      val stat = conn.createStatement()
      val rs = stat.executeQuery(sql)
      val array = new ArrayBuffer[T]
      while (rs.next()) {
        array += rowMapper.mapRow(rs)
      }
      array.toList
    } finally {
      conn.close
    }
  }

}
